package com.example.administrator.shzs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.shzs.R;
import com.example.administrator.shzs.utils.ToastUtils;
import com.example.administrator.shzs.app.MyApplication;
import com.example.administrator.shzs.url.Contents;
import com.example.administrator.shzs.ui.ForgetPasswordActivity;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 登陆界面
 */
public class LogInActivity extends BaseActivity implements View.OnClickListener {


    @Bind(R.id.iv_back_login_activity)
    ImageView ivBack;//返回键

    @Bind(R.id.et_user_number_login_activity)
    EditText etUserNumber;//账户名
    @Bind(R.id.et_user_password_login_activity)
    EditText etUserPassword;//密码
    @Bind(R.id.iv_forget_password_login_activity)
    ImageView ivForgetPassword;//忘记密码
    @Bind(R.id.btn_login_login_activity)
    Button btnLogin;//登陆
    @Bind(R.id.tv_register_login_activity)
    TextView tvRegister;//注册
    @Bind(R.id.tv_new_register_login_activity)
    TextView tvNewRegister;//新用户注册
    @Bind(R.id.tv_auth_code_login_login_activity)
    TextView tvAuthCodeLogin;//验证码登陆

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);
        ButterKnife.bind(this);
        MyApplication.app.activityList.add(this);
        //监听
        setListeners();
    }


    /**
     * 监听事件
     */
    private void setListeners() {

        ivBack.setOnClickListener(this);
        tvRegister.setOnClickListener(this);
        tvNewRegister.setOnClickListener(this);
        ivForgetPassword.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        tvAuthCodeLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        String username = etUserNumber.getText().toString().trim();
        String password = etUserPassword.getText().toString().trim();


        //正则表达式
        Pattern p = Pattern.compile("^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[06-8])\\d{8}$");
        //判断用户的手机号码格式是否正确
        Matcher m = p.matcher(username);
        boolean result = m.matches();

        switch (v.getId()) {

            case R.id.iv_back_login_activity://返回

                finish();

                break;

            case R.id.tv_register_login_activity://注册

                startActivity(new Intent(this, RegisterActivity.class));

                break;

            case R.id.tv_new_register_login_activity://新用户注册

                startActivity(new Intent(this, RegisterActivity.class));

                break;

            case R.id.iv_forget_password_login_activity://忘记密码

                startActivity(new Intent(this, ForgetPasswordActivity.class));

                break;


            case R.id.tv_auth_code_login_login_activity://手机验证码登陆

                break;

            case R.id.btn_login_login_activity://登陆

                if (!username.equals("") && !password.equals("") ) {

                    if(result) {
                        logIn(username, password);
                    }else {
                        ToastUtils.showMessageShort(this, "请输入正确的手机号");
                    }


                } else if (username.equals("")) {
                    ToastUtils.showMessageShort(this, "用户名不能为空");
                } else if (password.equals("")) {
                    ToastUtils.showMessageShort(this, "密码不能为空");
                }
                break;

        }
    }


    /**
     * 登录
     * @param username  账号
     * @param password  密码
     */
    private void logIn(final String username, String password) {

        String url = Contents.USER_LOGIN_URL;

        RequestParams params = new RequestParams(url);
        params.addBodyParameter("username",username);
        params.addBodyParameter("password",password);

        Log.i("Login",params+"");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {

                try {
                    JSONObject object = new JSONObject(result);
                    int state = object.getInt("state");

                    if (state == 1) {
                        String userId = object.getString("userid");
                        MyApplication.app.setUserId(userId);
                        MyApplication.app.setUserNumber(username);
                        //持久化保存
                        MyApplication.app.saveUserData();
                        ToastUtils.showMessageShort(LogInActivity.this, "登陆成功");

                        //反向传值结果码
                        setResult(RESULT_OK);

                        finish();
                        Log.i("***************userId=", "" + userId);
                    } else {
                        ToastUtils.showMessageShort(LogInActivity.this, "账号或密码错误");
                    }
                } catch (JSONException e) {

                    e.printStackTrace();

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }
}
